﻿using System;
using NUnit.Framework;
using Rhino.Mocks;
using TestCore.TestingHelpers;

namespace TestCore
{
    [TestFixture]
    public abstract class CoreTestBase
    {
        [TestFixtureSetUp]
        public virtual void TestFixtureSetUp()
        {
        }

        [TestFixtureTearDown]
        public virtual void TestFixtureTearDown()
        {
        }

        [SetUp]
        public virtual void SetUp()
        {
            mockRepository = new MockRepository();
            
        }

        [TearDown]
        public virtual void TearDown()
        {
            try
            {
                VerifyAll();
            }
            finally
            {
                FieldsCleanerCache.Clean(this);
            }
        }

        protected T GetMock<T>()
        {
            var mock = mockRepository.StrictMock<T>();
            mock.Replay();
            return mock;
        }

        protected T GetStub<T>()
        {
            var mock = mockRepository.Stub<T>();
            mock.Replay();
            return mock;
        }

        protected void VerifyAll()
        {
            mockRepository.VerifyAll();
            mockRepository.BackToRecordAll(BackToRecordOptions.None);
            mockRepository.ReplayAll();
        }

        protected IDisposable Ordered()
        {
            return new MockeryOrdered(mockRepository);
        }

        private MockRepository mockRepository;

        private class MockeryOrdered : IDisposable
        {
            public MockeryOrdered(MockRepository mockRepository)
            {
                this.mockRepository = mockRepository;
                ordered = mockRepository.Ordered();
            }

            public void Dispose()
            {
                ordered.Dispose();
                mockRepository.ReplayAll();
            }

            private readonly MockRepository mockRepository;
            private readonly IDisposable ordered;
        }
    }
}